package com.hddf.project.auth.dao_impl;

import org.bson.types.ObjectId;
import org.kommii.common_utils.DateTime_Utils;
import com.hddf.project.auth.dao.AESKeyDao_MongoDB;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.WriteConcern;

public class AESKeyDaoImpl_MongoDB implements AESKeyDao_MongoDB{
	//密钥对的有效时间 单位是秒
	public static final int AESKey_validTime = 60*5;
	
	/**
	 * 向mongodb 添加一个aes_key 返回一个mongodb 中的 _id
	 * @param aeskey
	 * @param coll
	 * @return
	 */
	public String add(String aeskey,DBCollection coll) {
		long current = DateTime_Utils.getCurrentSeconds();
		BasicDBObject entity = new BasicDBObject();
		entity.put("aes_key", aeskey);
		entity.put("aeskey_deadline", current+AESKey_validTime);
		coll.save(entity, WriteConcern.SAFE);
		String rs = ((ObjectId)entity.get("_id")).toString();
		return rs;
	}

	public boolean delete(String id,DBCollection coll) {
		ObjectId oid = new ObjectId(id);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query = queryBuilder.put("_id").is(oid).get();
		//使用 findAndRemove 方法会把被删除的对象返回 
		DBObject obj = coll.findAndRemove(query);
		if(null!=obj)
			return true;
		else
			return false;
	}

	public DBObject getById(String id,DBCollection coll) {
		ObjectId oid = new ObjectId(id);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query = queryBuilder.put("_id").is(oid).get();
		DBObject entity = coll.findOne(query);
		
		return entity;
	}
	
	public boolean deleteTimeOutAesKeys(long current_time,DBCollection coll){
		//coll.find(new BasicDBObject("aeskey_deadline", new BasicDBObject("$lt", current_time))).toArray();
		//List<DBObject> list = coll.find(new BasicDBObject("aeskey_deadline", new BasicDBObject("$lt", current_time))).toArray();
		//System.out.println(list.size());
		coll.remove(new BasicDBObject("aeskey_deadline", new BasicDBObject("$lt", current_time)));
		
		return true;
	}

	public static int getAESKey_validTime() {
		return AESKey_validTime;
	}

	
}
